package com.zrq.secondkill.service.impl;

import com.zrq.secondkill.service.UniqueIdService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author zrq
 */
@Service
public class UniqueIdServiceImpl implements UniqueIdService {

    private Integer currSeq =null;
    private Long lastTimeStamp=null;
    private static final int MID_SEQUENCE_LENGTH=6;

    @Value("${serverNo}")
    private String serverUniqueIdentifier;

    @PostConstruct
    public void init() {
        currSeq =0;
        lastTimeStamp=System.currentTimeMillis();
    }

    @Override
    synchronized public String generateUniqueId() {
        long currentTimeStamp=System.currentTimeMillis();

        Integer seq;
        if(currentTimeStamp==lastTimeStamp){
            seq= currSeq++;
        }else{
            lastTimeStamp=currentTimeStamp;
            currSeq=1;
            seq=0;
        }

        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(serverUniqueIdentifier);
        stringBuilder.append(currentTimeStamp);

        //扩充序列号为指定位数
        String s = String.valueOf(seq);
        for (int i = 0; i < MID_SEQUENCE_LENGTH - s.length(); ++i) {
            stringBuilder.append(0);
        }
        stringBuilder.append(s);

        return stringBuilder.toString();
    }
}
